import store from '@/store'
import { on } from 'element-ui/src/utils/dom'
import { Notification } from 'element-ui';

function checkPermission(el, binding, vnode) {
    const { arg, value } = binding;
    const thisPath = vnode.context.$route.meta && vnode.context.$route.meta.authLink;
    const { adminInfo, adminAuth } = store.getters && store.getters;
    const hasPermission = !thisPath || adminAuth.some(item => item.authorityUrl === thisPath && item[`authority${value}`] === 1);
    if (adminInfo.adminId !== 1 && !hasPermission) {
        // 禁用 click 兼容性检测
        if (!vnode.componentInstance) {
            alert('v-permission 不支持用在普通dom元素')
            return
        }
        if (vnode.data.nativeOn && vnode.data.nativeOn.click) {
            alert('v-permission 不支持 click.native')
            return
        }

        // 禁用点击事件(组件）
        if (vnode.componentInstance) {
            vnode.componentInstance.$off('click')
        }

        on(el, 'click', function(e) {
            e.preventDefault()
            e.stopPropagation()
            Notification({
                type: 'error',
                title: '无权限',
                message: '权限不足，无法继续操作'
            })
        })
    }
}

export default {
    inserted(el, binding, vnode) {
        checkPermission(el, binding, vnode)
    }
}
